package system

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/os/gfile"
	"path/filepath"
	"server/internal/dao"
	"server/internal/model"
	"server/internal/model/do"
	"server/internal/model/entity"
	"server/internal/service"
)

type sSystemLog struct{}

func init() {
	service.RegisterSystemLog(&sSystemLog{})
}

func (s *sSystemLog) Create(ctx context.Context, in do.SystemHttpLog) (id int64, err error) {
	return dao.SystemHttpLog.Ctx(ctx).Data(in).InsertAndGetId()
}

func (s *sSystemLog) HttpList(ctx context.Context, in model.SystemHttpListInput) (items []entity.SystemHttpLog, total int, err error) {
	items = make([]entity.SystemHttpLog, 0)
	where := g.Map{}
	if len(in.Method) > 0 {
		where["method"] = in.Method
	}
	if len(in.Route) > 0 {
		where["route"] = in.Route
	}
	if len(in.TraceId) > 0 {
		where["trace_id"] = in.TraceId
	}
	err = dao.SystemHttpLog.Ctx(ctx).Where(where).Page(in.Page, in.PageSize).OrderDesc("id").ScanAndCount(&items, &total, true)

	return
}

func (s *sSystemLog) LogFiles(ctx context.Context) map[string][]string {
	logs := make(map[string][]string)
	logs = map[string][]string{
		"crontab":     make([]string, 0),
		"crontabTask": make([]string, 0),
		"websocket":   make([]string, 0),
	}
	for logName, _ := range logs {
		loggerPath := g.Log(logName).GetPath()
		logFiles, _ := gfile.ScanDir(loggerPath, "*", true)
		files := make([]string, 0)
		for _, f := range logFiles {
			if gfile.IsFile(f) {
				files = append(files, filepath.ToSlash(f))
			}
		}
		logs[logName] = files
	}
	return logs
}
